//
//  SandBox.m
//  SeseNews
//
//  Created by Sese on 15/7/23.
//  Copyright (c) 2015年 Sese工作室. All rights reserved.
//

#import "SandBox.h"


@implementation SandBox


static SandBox *sQH = nil;
+(SandBox *)sharedSqliteDataHandele{
    //加上线程锁保证访问安全；
    @synchronized(self){
        if (nil == sQH) {
            sQH = [[SandBox alloc]init];
        }
        return sQH;
    }
}


static sqlite3 *sq = nil;

//实现打开数据库的方法
-(void)openSqlite{
    // 1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"Sese.sqlite"];
    
    int openResult = sqlite3_open([path UTF8String], &sq);

    if (openResult != SQLITE_OK) {
        NSLog(@"打开数据库失败");
        return;
    }
 
    NSString *creatSQL = @"CREATE TABLE IF NOT EXISTS Sese (id integer PRIMARY KEY,data blob NOT NULL,urlString text NOT NULL);";
    
    char *error = nil;
    //创表
    int result = sqlite3_exec(sq, [creatSQL UTF8String], NULL, NULL, &error);
    
    //3、判断表是否创建成功
    if (result == SQLITE_OK) {
        NSLog(@"数据表创建成功");
    }else{
        NSLog(@"数据表创建失败：%s",error);
    }
    
    
}

#pragma marl - 实现关闭数据 -
-(void)closeSqlite{
    int result = sqlite3_close(sq);
    if (result == SQLITE_OK) {
        sq = nil;
    }
}

#pragma mark - 插入信息 -
-(void)insertData:(NSString *)data UrlString:(NSString *)urlString{
    
    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO Sese(data,urlString) values('%@','%@')",data,urlString];

    char *error = nil;
    int result = sqlite3_exec(sq, [insertSQL UTF8String], nil, nil, &error);
    //3、判断
    if (result == SQLITE_OK) {
        NSLog(@"插入成功");
    }else{
        NSLog(@"插入失败：%s",error);
    }
    
}

#pragma mark - 查询所有用户 -
-(NSData *)selectAllUrlString:(NSString *)urlString{
    NSString *selectSQL = [NSString stringWithFormat: @"select *from text where urlString = '%@'",urlString];
    sqlite3_stmt *stmt = nil;
    int result = sqlite3_prepare_v2(sq, [selectSQL UTF8String], -1, &stmt, nil);
    NSData *dataData=nil;
    
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            
            char *data = (char *)sqlite3_column_text(stmt, 0);
            
            NSString *dataStr = [NSString stringWithUTF8String:data];
            
            dataData = [[NSData alloc]initWithBase64EncodedString:dataStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
        }
        
    }else{
        NSLog(@"执行错误");
    }
    
    sqlite3_finalize(stmt);
 
    return dataData;
}


@end
